package com.kzd.gtgame

import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.*
import com.kzd.gtgame.app.GT_FORCE_LOGIN
import com.kzd.gtgame.app.SPSConstance
import com.kzd.gtgame.base.BaseViewModel
import com.kzd.gtgame.custom.setOnClickAntiShakeListener
import com.kzd.gtgame.entity.IsLogin
import com.kzd.gtgame.main.*
import com.kzd.gtgame.main.game.GameH5Activity
import com.kzd.gtgame.main.home.HomeFeaturedFragment
import com.kzd.gtgame.main.home.adapter.HomeFabAdapter
import com.kzd.gtgame.main.popup.AppUpDatePopup
import com.kzd.gtgame.main.popup.GiftImagePopup
import com.kzd.gtgame.main.popup.ProgressPopup
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.owner.OwnerViewModeActivity
import com.umeng.umlink.MobclickLink
import com.umeng.umlink.UMLinkListener
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Flowable
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*
import java.lang.Exception
import java.util.*
import java.util.concurrent.TimeUnit

class MainActivity : OwnerViewModeActivity<BaseViewModel>() {

    private val mHomeFabAdapter = HomeFabAdapter()

    private val mGiftImagePopup: GiftImagePopup by lazy {
        GiftImagePopup(context = this) { _, homeFab ->
            toMineRichTextActivityUrl(
                title = homeFab.title, url = homeFab.url,
                isLogin = homeFab.is_login == 1,
                action = AccessAction.LOGIN_FAB
            )
        }
    }
    private var isGiftImagePopupShow: Boolean = false

    private val fragmentLifecycleCallbacks = object : FragmentManager.FragmentLifecycleCallbacks() {

        override fun onFragmentViewCreated(
            fm: FragmentManager, fragment: Fragment, v: View, savedInstanceState: Bundle?,
        ) {
            super.onFragmentViewCreated(fm, fragment, v, savedInstanceState)
            if (fragment !is HomeFeaturedFragment) {
                return
            }
            fragment.viewModel.indexHomeLiveData.observe(fragment.viewLifecycleOwner, { response ->
                if (response.status != Status.SUCCESS)
                    return@observe
                val data = response.data?.data
                    ?: return@observe
                if (data.isNullOrEmpty()) {
                    return@observe
                }
                fabMainActivity.visibility = View.VISIBLE



                viewModel.userAppFab()
            })
        }

        override fun onFragmentResumed(fm: FragmentManager, fragment: Fragment) {
            super.onFragmentResumed(fm, fragment)
            when (fragment) {
                is MainHomeFragment -> {
                    BarUtils.setStatusBarLightMode(fragment.requireActivity(), (false))

                    val distance = fragment.viewModel.changeBarStyleLiveData.value ?: 0
                    val alpha = if (distance > 255) 255 else distance
                    val color = Color.argb(alpha, 41, 131, 255)
                    BarUtils.setStatusBarColor(fragment.requireActivity(), color)

                }
                is HomeFeaturedFragment -> {
                    val data = fragment.viewModel.indexHomeLiveData.value?.data?.data
                    if (!data.isNullOrEmpty()) {
                        fabMainActivity.visibility = View.VISIBLE
                    }
                }
                is MainGameFragment -> {
                    fabMainActivity.visibility = View.GONE
                    BarUtils.setStatusBarLightMode(fragment.requireActivity(), (false))
                    BarUtils.setStatusBarColor(
                        fragment.requireActivity(),
                        ColorUtils.getColor(R.color.colorMain)
                    )
                }
                is MainMoneyFragment -> {
                    fabMainActivity.visibility = View.GONE
                    BarUtils.setStatusBarLightMode(fragment.requireActivity(), (false))
                    BarUtils.setStatusBarColor(fragment.requireActivity(), Color.TRANSPARENT)
                }
                is MainServiceFragment -> {
                    fabMainActivity.visibility = View.GONE
                    BarUtils.setStatusBarLightMode(fragment.requireActivity(), (false))
                    BarUtils.setStatusBarColor(fragment.requireActivity(), Color.TRANSPARENT)
                }
                is MainMineFragment -> {
                    fabMainActivity.visibility = View.GONE
                    BarUtils.setStatusBarLightMode(fragment.requireActivity(), (false))
                    BarUtils.setStatusBarColor(fragment.requireActivity(), Color.TRANSPARENT)
                }
            }
        }

    }

    private val mProgressPopup: ProgressPopup by lazy {
        ProgressPopup(context = this, onCancel = {}, onConfirm = {})
    }

    private val mAppUpDatePopup: AppUpDatePopup by lazy {
        AppUpDatePopup(context = this, onClick = {
            mAppUpDatePopup.dismiss()
            val fileUrl = viewModel.userAppUpdateLiveData.value
                ?.data?.data?.apk_file_url ?: return@AppUpDatePopup
            viewModel.userDownload(fileUrl) {
                mProgressPopup.setProgress(it)
            }
        })
    }

    private var mExitTime: Long = 0

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                toast("再按一次退出程序")
                mExitTime = System.currentTimeMillis()
            } else {
                onBackPressed()
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun viewModel(): BaseViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.activity_main

    override fun initView() {

        val mainFragments: MutableList<Fragment> = mutableListOf(
            MainHomeFragment.newInstance(),
            MainGameFragment.newInstance(),
            MainMoneyFragment.newInstance(),
            MainServiceFragment.newInstance(),
            MainMineFragment.newInstance()
        )

        view_pager_main.offscreenPageLimit = mainFragments.size
        view_pager_main.setScrollAnim(false)
        view_pager_main.adapter = object : FragmentStatePagerAdapter(
            supportFragmentManager,
            BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
        ) {
            override fun getCount(): Int {
                return mainFragments.size
            }

            override fun getItem(position: Int): Fragment {
                return mainFragments[position]
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            }
        }

        nav_view_main.setOnNavigationItemSelectedListener { item ->
            val position = when (item.itemId) {
                R.id.item_main_game -> 1
                R.id.item_main_money -> if (checkLogin()) 2 else {
                    toAccessActivity()
                    return@setOnNavigationItemSelectedListener false
                }
                R.id.item_main_service -> 3
                R.id.item_main_mine -> 4
                else -> 0
            }
            view_pager_main.currentItem = position
            return@setOnNavigationItemSelectedListener true
        }

        supportFragmentManager.registerFragmentLifecycleCallbacks(
            fragmentLifecycleCallbacks,
            (true)
        )

        rvMainFabBody.apply {
            layoutManager = LinearLayoutManager(context)
        }.adapter = mHomeFabAdapter

        mHomeFabAdapter.setOnItemClickListener { _, _, position ->
            val itemDate = mHomeFabAdapter.getItem(position)
            toMineRichTextActivityUrl(
                title = itemDate.title, url = itemDate.url,
                isLogin = itemDate.is_login == 1,
                action = AccessAction.LOGIN_FAB
            )
        }

        mHomeFabAdapter.setOnDownTimeListener { textView, endTime ->
            val disposable =
                Flowable.intervalRange((1), endTime.toLong(), (0), (1), TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnNext {
                        textView.text = millis2FitTimeSpan(((endTime - it) * 1000), (3))
                    }
                    .doOnComplete {
                        viewModel.userAppFab()
                    }
                    .subscribe()
            viewModel.dispose.add(disposable)
        }

        ivMainFabCoupon.setOnClickAntiShakeListener {
            toMineCouponActivity()
        }

        //跳转消息列表
        barMainMessage.setOnClickAntiShakeListener {
            toMineMessageActivity()
        }
    }

    override fun initData() {
        MobclickLink.getInstallParams(this as Context, false, MainUMLinkListener())
        viewModel.userAppUpDate(delay = 5000)
        startTimer()
    }

    override fun onRestart() {
        super.onRestart()
        startTimer()
    }

    override fun onStop() {
        super.onStop()
        cancelTimer()
    }

    override fun initViewMode() {
        viewModel.userAppUpdateLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            val data = response.data?.data
                ?: return@observe
            mAppUpDatePopup.setContent(data.update_log)
                .showPopupWindow()
        })
        viewModel.userDownloadLiveData.observe(this as LifecycleOwner, { response ->
            when (response.status) {
                Status.START -> {
                    mProgressPopup.resetProgress()
                    mProgressPopup.showPopupWindow()
                }
                Status.FAILURE -> {
                    mProgressPopup.dismiss()
                    toast(response.error?.msg)
                }
                Status.SUCCESS -> {
                    mProgressPopup.dismiss()
                    val data = response.data?.data
                        ?: return@observe
                    AppUtils.installApp(data)
                }
            }
        })

        viewModel.userAppFabLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            if (data.size > 0 && !isGiftImagePopupShow) {
                mGiftImagePopup.setFillData(data[0])
                    .showPopupWindow()
                isGiftImagePopupShow = true
            }
            mHomeFabAdapter.setNewInstance(data)
        })

        BaseViewModel.userAppTipsLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            if (data.coupon_unread > 0) {
                viewMainFabCouponRead.visibility = View.VISIBLE
            } else {
                viewMainFabCouponRead.visibility = View.GONE
            }
            if (data.msg_rs != 1) {
                mMotionLayout.transitionToState(R.id.startBar)
            } else {
                mMotionLayout.transitionToState(R.id.endBar)
            }
            tvMainMessageTipsName.text = data.msg_name
            tvMainMessageTipsSub.text = data.msg_title
        })

    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val mIndex = try {
            (intent?.extras?.getString(KEY_MAIN_INDEX) ?: "0").toInt()
        } catch (e: Exception) {
            0
        }
        when (mIndex) {
            4 -> nav_view_main.selectedItemId = R.id.item_main_mine
            3 -> nav_view_main.selectedItemId = R.id.item_main_service
            2 -> nav_view_main.selectedItemId = R.id.item_main_money
            1 -> nav_view_main.selectedItemId = R.id.item_main_game
            else -> nav_view_main.selectedItemId = R.id.item_main_home
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        supportFragmentManager.unregisterFragmentLifecycleCallbacks(fragmentLifecycleCallbacks)
    }


    override fun onEventMainThread(any: Any) {
        if (any is IsLogin) {
            isGiftImagePopupShow = false
            ActivityUtils.finishActivity(GameH5Activity::class.java)
            if (!any.isLogin && GT_FORCE_LOGIN) {
                toAccessActivity(AccessAction.LOGIN_CHANNEL)
            } else {
                viewModel.userAppFab()
            }
        }
    }

//    private val mTimerTask: TimerTask
//        get() = object : TimerTask() {
//            override fun run() {
//                viewModel.userAppTips()
//            }
//        }
//
//    private var mTimer: Timer? = null

    private fun startTimer() {
//        mTimer = Timer()
//        mTimer?.schedule(mTimerTask, 0, 5000)
        viewModel.userAppTips()
    }

    private fun cancelTimer() {
//        mTimer?.cancel()
    }

    private fun millis2FitTimeSpan(millisValue: Long, precisionValue: Int): String? {
        var millis = millisValue
        var precision = precisionValue
        if (precision <= 0) return null
        precision = Math.min(precision, 5)
        val units = arrayOf("天", "时", "分", "秒", "毫秒")
        if (millis == 0L) return "0+${units[precision - 1]}"
        val sb = StringBuilder()
        if (millis < 0) {
            sb.append("-")
            millis = -millis
        }
        val unitLen = intArrayOf(86400000, 3600000, 60000, 1000, 1)
        for (i in 0 until precision) {
            val mode = millis / unitLen[i]
            millis -= mode * unitLen[i]
            sb.append(mode).append(units[i])
        }
        return sb.toString()
    }

    inner class MainUMLinkListener : UMLinkListener {
        override fun onLink(p0: String?, p1: HashMap<String, String>?) {
            LogUtils.e("==onLink==p0:${p0}====p1:${GsonUtils.toJson(p1)}")
        }

        override fun onInstall(p0: HashMap<String, String>?, p1: Uri?) {
            val memberId = p1?.getQueryParameter("member_id")
                ?: return
            SPSConstance.memberId = memberId
            val content = "content://com.kzd.gtgame.provider/GameMember"
            val uri = Uri.parse(content)
            contentResolver.delete(uri, (null), (null))
            val values = ContentValues().apply {
                put("member", memberId)
            }
            contentResolver.insert(uri, values)
        }

        override fun onError(p0: String?) {
            LogUtils.e("==onError==p0:${p0}")
        }
    }


}